<template>
  <div class="login-bg">
    <video
      src="../../assets/video/ltnI1wLVjdqmBWbtlZdEMwG7KohR-1050x.mp4"
      loop="loop"
      muted
      autoplay="true"
    ></video>
    <div class="login-from">
      <svg @click="change" class="icon qrCode" aria-hidden="true">
        <use
          :xlink:href="
            LoginModal && smsLogin
              ? '#icon-diannaojiaobiao'
              : '#icon-erweimajiaobiao'
          "
        ></use>
      </svg>
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="demo-loginForm"
      >
        <h1>峰峰智慧后台</h1>
        <div v-if="LoginModal && !smsLogin">
          <el-form-item label="账号" prop="count">
            <el-input
              type="text"
              v-model="loginForm.count"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input
              type="password"
              v-model="loginForm.pass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha" class="loginCaptcha">
            <el-input
              @keydown.native.enter="submitForm('loginForm')"
              v-model="loginForm.captcha"
            ></el-input>
            <span v-loading="codeLoading" class="captcha captcha-svg">
              <i v-html="captchaSvg" @click="updateCaptcha"></i>
            </span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')">
              提交
            </el-button>
          </el-form-item>
          <div class="smsLogin">
            <a href="#" @click="smsLogin = !smsLogin">
              <svg class="icon smsLogin" aria-hidden="true">
                <use xlink:href="#icon-shouji-iphone12-zhengmian"></use>
              </svg>
              切换短信登录
            </a>
          </div>
        </div>

        <div v-if="!LoginModal && !smsLogin" class="demo-loginForm">
          <h2>扫码登录</h2>
          <div v-loading="qrLoading" class="img">
            <img :src="qrImgUrl" />
            <i
              @click="freshQrcode"
              class="mask"
              :style="qrStyle"
              v-show="qrMask"
            ></i>
          </div>
        </div>

        <div class="smsContainer" v-if="smsLogin">
          <h2>短信登录</h2>
          <el-form-item label="手机号">
            <el-input
              maxlength="11"
              v-model="phoneNumber"
              class="captcha phone"
            ></el-input>
            <span
              v-text="smsSend ? '点击发送验证码' : `${smsTime}秒后重新发送`"
              @click="sendSmsCode"
              class="captcha-svg"
              style="color: #888; line-height: 45px; text-decoration: underline"
            ></span>
          </el-form-item>
          <el-form-item label="验证码">
            <el-input v-model="smsCode"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="smsSubmit">提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
/deep/.captcha-svg {
  width: 100px;
  position: absolute;
  right: 13px;
  top: -3px;
}

.qrCode {
  width: 5em;
  height: 5em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  float: right;
  color: #ccc;
}
div.smsLogin {
  width: 150px;
  height: 4em;
  margin: 0 auto;
  a {
    color: #fff;
    font-size: 17px;
    text-decoration: none;
    line-height: 1.6em;
    .smsLogin {
      width: 1.5em;
      height: 1.5em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
      color: #ccc;
      float: left;
    }
  }
}

video {
  height: 1080px;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
.login-from {
  color: #fff;
  width: 500px;
  height: 500px;
  position: fixed;
  //   right: 200px;
  //   bottom: 150px;
  bottom: 0px;
  right: 0px;
  background-color: rgba(0, 0, 0, 0.6);
  .demo-loginForm {
    position: absolute;
    left: 0;
    top: 50px;
    bottom: 0;
    right: 0;
    margin: auto;
    .el-button {
      width: 275px;
      background: linear-gradient(90deg, #1596fb, #002dff);
    }
    div.img {
      width: 240px;
      height: 240px;
      position: absolute;
      left: 0;
      top: 100px;
      bottom: 100px;
      right: 0;
      margin: auto;
      text-align: center;
      img {
        position: absolute;
        left: 0;
        width: 240px;
        height: 240px;
      }
      /deep/i.mask {
        height: 240px !important;
        width: 240px !important;
        background-color: #fff;
        display: block;
        opacity: 0.8;
        position: absolute;
        cursor: pointer;
      }
    }
    h1 {
      text-align: center;
      margin-bottom: 60px;
    }
    h2 {
      text-align: center;
    }
    /deep/.el-form-item__label {
      color: white;
    }
    /deep/.el-form-item {
      width: 380px;
      &.loginCaptcha {
        .el-input {
          width: 130px;
        }
        .captcha {
          width: 140px;
          height: 40px;
          float: right;
          background-color: #fff;
          border-radius: 4px;
          right: 0;
          top: 0;
          svg {
            width: 140px;
            height: 40px;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
<script>
import * as api from "@/api/users";

import png1 from "../../assets/img/scancode.png";
import png2 from "../../assets/img/invalidQr.png";

import socketIo from "socket.io-client";
import qr from "qrcode";

import { mapMutations } from "vuex";

var validateCount = (rule, value, callback) => {
  if (!/^[0-9A-Za-z_]{3,12}/.test(value)) {
    callback(new Error("由数字、字母、下划线组成的6-12位"));
  } else {
    callback();
  }
};

var validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    callback();
  }
};

var ckeckCaptcha = (rule, value, callback) => {
  if (/^[0-9A-Za-z]{3,5}/.test(value)) {
    callback();
  } else {
    callback(new Error("请输入验证码"));
  }
};
var localStorageRes = (res) => {
  localStorage.setItem("qf-token", res.data.token);
  //   localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
  localStorage.setItem(
    "qf-permission",
    JSON.stringify(res.data.permission.buttons)
  );
};

export default {
  name: "login",
  meta: {
    title: "",
  },
  data() {
    return {
      captchaSvg: "",
      codeLoading: true,
      LoginModal: true,
      qrLoading: false,
      qrImgUrl: "",
      qrMask: false,
      smsLogin: false,
      phoneNumber: "",
      smsCode: "",
      smsSend: true,
      smsTime: 10,
      qrStyle: {
        background: `#fff url(${png1}) center/100px no-repeat`,
      },
      loginForm: {
        count: "",
        pass: "",
        captcha: "",
      },
      rules: {
        count: [{ validator: validateCount, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: ckeckCaptcha, trigger: "blur" }],
      },
    };
  },
  created() {
    this.updateCaptcha();
  },
  methods: {
    ...mapMutations(["SET_USERINFO"]),

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在登录...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          api.verifyCaptcha(this.loginForm.captcha).then(async (rescaptcha) => {
            if (rescaptcha.data.state) {
              await api
                .countLogin(this.loginForm.count, this.loginForm.pass)
                .then((res) => {
                  if (res.data.state) {
                    localStorageRes(res);
                    this.SET_USERINFO(res.data.userInfo);
                    // this.$$store.emmit()
                    this.$message({
                      duration: 1000,
                      message: res.data.msg,
                      type: "success",
                    });
                    loading.close();
                    //跳转页面
                    this.$router.push("/welcome");
                  } else {
                    loading.close();
                  }
                });
            } else {
              this.updateCaptcha();
              loading.close();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    updateCaptcha() {
      this.codeLoading = true;
      api.getCaptcha().then((res) => {
        let { img } = res.data;
        this.captchaSvg = img;
        this.codeLoading = false;
      });
    },
    change() {
      this.LoginModal = !this.LoginModal;
      this.qrLoading = true;
      if (this.smsLogin) {
        this.smsLogin = !this.smsLogin;
        this.LoginModal = !this.LoginModal;
      }
    },
    async freshQrcode(sid) {
      this.qrLoading = true;
      sid = localStorage.getItem("sid") ?? sid;
      let { scanCodeUrl, state: freshQrState } = (await api.freshQrcode(sid))
        .data;
      if (freshQrState) {
        qr.toDataURL(scanCodeUrl, (err, qrImgUrl) => {
          if (err) return this.$messageBox.error(err);

          this.qrImgUrl = qrImgUrl;
          this.qrMask = false;
          this.qrLoading = false;
        });
      }
    },
    async sendSmsCode() {
      let timer = 0;
      if (this.smsTime != 10) return;
      let smsResult = await api.getSmsCode(this.phoneNumber);
      if (smsResult.data.state) {
        this.$message.success("短信发送成功");
        timer = setInterval(() => {
          this.smsTime--;
          this.smsSend = false;
          if (this.smsTime === 0) {
            this.smsTime = 10;
            this.smsSend = true;
            clearTimeout(timer);
          }
        }, 1000);
      }
    },
    smsSubmit() {
      api.smsLogin(this.smsCode).then((res) => {
        const loading = this.$loading({
          lock: true,
          text: "正在登录...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        if (res.data.state) {
          loading.close();
          localStorageRes(res);

          this.$message({
            type: "success",
            duration: 1000,
            message: res.data.msg,
          });
          loading.close();
          //跳转页面
          this.$router.push("/welcome");
        } else {
          loading.close();
        }
      });
    },
    openFullScreen2() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, 2000);
    },
  },
  watch: {
    LoginModal(newVal, oldVal) {
      if (!newVal) {
        let io = socketIo("wss://chst.vip");
        io.on("connectSuccess", async (dataConnection) => {
          localStorage.setItem("sid", dataConnection.sid);
          let sid = dataConnection.sid;
          this.freshQrcode(sid);
        });
        io.on("scancodeSuccess", async (data) => {
          this.qrStyle.background = `#fff url(${png1}) center/100px no-repeat`;
          this.qrMask = true;
          if (data.state) {
            await api.qrvLogin(data.wechatCode).then((res) => {
              if (res.data.state) {
                localStorageRes(res);

                this.qrMask = false;
                this.$router.push("/welcome");
              }
            });
          }
        });
        io.on("invalidCode", (data) => {
          if (!data.state) {
            this.qrStyle.background = `#fff url(${png2}) center/100px no-repeat`;
            this.qrMask = true;
          }
        });
      }
    },
  },
};
</script>
